//copyright (c) 2016 L.W.C.<lwc@li.cm>
#include "vxin_rubbish.h"

int RUBcomp(void*ptrA,void*ptrB){
	if(!ptrA)return 0;
	return ptrA==ptrB;
}

vxin_slist* RUB_Init(){
	return SLIST_New(0,0);
}

void RUB_Quit(vxin_slist* stack){
	while(stack->next){
		if(stack->ptr){
			free(stack->ptr);
			SLIST_Pop(stack,0,0);
		}
		stack=stack->next;
	}
	if(stack->ptr)free(stack->ptr);
	
	SLIST_Destroy(stack);
}

void* RUB_malloc(vxin_slist *stack,size_t size){
	void *newptr;
	newptr=malloc(size);
	if(!newptr){
		return 0;
	}
	SLIST_Push(stack,newptr,0);
	return newptr;
}

void* RUB_realloc(vxin_slist *stack,void *ptr,size_t size){
	void *newptr;
	newptr=realloc(ptr,size);
	if(!newptr){
		return 0;
	}
	if(ptr!=newptr)
	{
		SLIST_Push(stack,newptr,0);
	}
	return newptr;
}

void RUB_clean(vxin_slist *stack){
	vxin_slist *temp;
	temp=stack;
	while(temp){
		if(temp->id==0&&temp->ptr!=0){
			free(temp->ptr);
			SLIST_Pop(temp,0,0);
		}
		else{
			temp->id--;
		}
		temp=temp->next;
	}
}

void RUB_using(vxin_slist *stack,void *ptr,int power){
	vxin_slist *temp;
	temp=SLIST_GetByPtr(stack,ptr,&RUBcomp);
	if(!temp){
		return;
	}
	temp->id=power;
}

int RUB_living(vxin_slist *stack,void *ptr){
	return (int)SLIST_GetByPtr(stack,ptr,&RUBcomp);
}